﻿using System;
using System.Web.SessionState;
using System.Web;

namespace Communicate
{
    public class WebServiceHandler : IHttpHandler, IRequiresSessionState
    {
        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext httpContext)
        {

            object result = null;
            try
            {
                byte[] data = new byte[httpContext.Request.InputStream.Length];
                httpContext.Request.InputStream.Read(data, 0, data.Length);
                object context = CommunicateManage.GetContext(httpContext.Session);
                object obj = Serializer.Deserialize(data);
                if (obj is LoginRequest)
                {
                    LoginRequest loginRequest = obj as LoginRequest;
                    result = CommunicateManage.Login(loginRequest.UserName, loginRequest.Password, httpContext.Session);
                }
                else
                {
                    if (context == null)
                        result = new CommunicateException(ExceptionType.Timeout, "Session为空，您还没有登录或者离开的时间太长！");
                    else
                        result = CommunicateManage.Invoke((InvokeEntity)obj, context);
                }
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                    result = new CommunicateException(ExceptionType.External, ex.InnerException);
                else
                    result = new CommunicateException(ExceptionType.Internal, ex);
            }
            byte[] resultData = Serializer.Serialize(result);
            if (resultData != null && resultData.Length > 0)
            {
                httpContext.Response.OutputStream.Write(resultData, 0, resultData.Length);
            }
            httpContext.Response.OutputStream.Flush();
        }
    }
}
